<?php
use \GatewayWorker\Lib\Gateway;
use \Core\Threeyyy;
use \Core\Swimming;
class Events{
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据
        Gateway::sendToClient($client_id, json_encode(array(
            'type'      => 'init',
            'client_id' => $client_id
        )));
        // 向所有人发送
//        Gateway::sendToAll("$client_id login");
    }

   public static function onMessage($client_id, $message){


        $message_data = json_decode($message, true);
        $redis = new Redis();
        $redis->connect("127.0.0.1",6379);
        if(!$message_data){
            return ;
        }
        switch($message_data['type']){
            case 'ping':
                return;
				break;
            case 'send_to_all' :
                return  Gateway::sendToAll($message_data['message']);
                break;
            case 'send_to_id' :
                $message_data['message_status'] = 'save';
                if(!Gateway::isUidOnline($message_data['toid']))
                {
                    // 保存未读消息
                    $message_data['status'] = 1;
                    var_dump($message_data);
                    Gateway::sendToUid($message_data['id'], json_encode($message_data));
                }
                else{
                     //在线就转发消息给对应的uid
                    if ($message_data['onpage']){
                        $message_data['status'] = 1;
                    }else{
                        $message_data['status'] = 2;
                    }

                    var_dump($message_data);
                    Gateway::sendToUid($message_data['toid'], json_encode($message_data));
//                    savechat($message_data);

                }
                break;
            case 'send_to_client' :
                return  Gateway::sendToClient($message_data['client_id'], $message_data);
                break;
            case 'bind_id' :
                $message_data['message_status'] = 'bindsuccess';
                if (Gateway::bindUid($message_data['client_id'],$message_data['id'])){
                   Gateway::sendToUid($message_data['id'],json_encode($message_data) );
                }
                break;
            default:
                return  Gateway::sendToAll($message_data['message']);
                break;
        }
   }
   public static function onClose($client_id){
   }
}